import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { BaseHttpService } from '../../../../shared/services/baseHttp.service';
import { PortfolioSharingStatus, PortfolioFilterModel, PortfolioType } from './portfolio.model';
import { StorageService } from '../../../../shared/services/storage.service';

export enum PortfolioUniversesType {
    'My portfolios' = 0,
    'Shared portfolios' = 1,
    'Universes' = 2,
    'System portfolios' = 3
}

/**
 * TODO: once the portfoliosubscription method is used in a more decent way, move the analytics ebacon outside this and delte the service import
 */
@Injectable()
export class PortfolioService extends BaseHttpService {
    private portfolioServiceLink: string = 'portfolioserv/api/v1/portfolios';
    private portfolioMonitoringLink: string = 'portfolioserv/api/v1/subscribetoportfolio';
    constructor(private http: HttpClient) {
        super();
    }

    /**
     * Get number of portoflio after the input filter is applied
     * @param filters Portofolio list filter object
     */
    public getPortfolioCount(filters: PortfolioFilterModel, portfolioType: PortfolioType = PortfolioType.Custom): Observable<number> {
        let userInfo = StorageService.get().userInfo;

        let params: HttpParams = new HttpParams();
        params = params.set('isMyPortfolio', 'true')
            .set('namePortfolio', filters.namePortfolio)
            .set('sharingStatus', filters.sharingStatus.valueOf().toString())
            .set('portfolioType', portfolioType.valueOf().toString())
            .set('isNameEqual', filters.isNameEqual.toString())
            .set('newVersion', 'true')
            .set("userId", userInfo.userId)
            .set("accountId", userInfo.accountId);

        let listOptions: any = {
            includeAllFields: false,
            getCount: true
        };

        params = this.urlEncodeObject(listOptions, params);

        return this.http.get<number>(this.serverUrl + this.portfolioServiceLink, { params: params });
    } 

    public savePortfolio(filterId: string, portfolioId: string, portfolioName: string, isShared: boolean, update: boolean) {
        let body = {
            filterId: filterId,
            isValid: true,
            portfolioId: portfolioId,
            portfolioName: portfolioName,
            sharingStatus: (isShared ? PortfolioSharingStatus.Shared : PortfolioSharingStatus.Private)
        };

        if (update)
            return this.http.put(this.serverUrl + 'screeningtoolserv/api/v1/portfolios', body, { responseType: 'text' });
        else
            return this.http.post(this.serverUrl + 'screeningtoolserv/api/v1/portfolios', body, { responseType: 'text' });
    }   
}